package binarytree;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

/**
 * @Author: 海琳琦
 * @Date: 2022/2/19 11:28
 * https://leetcode-cn.com/problems/find-largest-value-in-each-tree-row/
 * 给定一棵二叉树的根节点 root ，请找出该二叉树中每一层的最大值。
 */
public class LargestValues {
    class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        public TreeNode() {
        }

        public TreeNode(int val) {
            this.val = val;
        }

        public TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    public List<Integer> largestValues(TreeNode root) {
        List<Integer> result= new ArrayList<>();
        Queue<TreeNode> levelNodes = new LinkedList<>();
        if (root != null) {
            levelNodes.offer(root);
        }
        while (!levelNodes.isEmpty()) {
            int size = levelNodes.size();
            int max = Integer.MIN_VALUE;
            for (int i = 0; i < size; i++) {
                TreeNode poll = levelNodes.poll();
                if (poll.val > max) {
                    max = poll.val;
                }
                if (poll.left != null) {
                    levelNodes.offer(poll.left);
                }
                if (poll.right != null) {
                    levelNodes.offer(poll.right);
                }
            }
            result.add(max);
        }
        return result;
    }

    public static void main(String[] args) {

    }
}
